// import './App.css';
import React, { Component } from 'react';
import { Space, Table, Popconfirm, Button, Input, Divider, Form, Drawer, message,Image } from 'antd';
import axios from 'axios';
import { render } from '@testing-library/react';
import get from "../api/api"
import { nanoid } from "nanoid";

class Class extends Component {
    formRef = React.createRef() //清空输入框内容
    formRef1 = React.createRef()
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            visible1: false,
            rowid: null,
            text: null,
            image: null,
            imageUrl: "",
            columns: [
                {
                    title: '图片', dataIndex: '', key: 'imageurl', render: (record) => {

                        return record.imageurl ? <Image src={record.imageurl} style={{ maxWidth:'200px' }} /> : <p>暂无图片</p>
                    }
                },
                
                {
                    title: '操作',
                    key: 'action',
                    render: (_, record) => (
                        <Space size="middle">
                            
                            <Popconfirm title="确定要删除吗?" onConfirm={this.deleteData.bind(this, record.objectId)} onCancel={this.onClose.bind(this)} okText="确定" cancelText="取消" >
                                <a className="action-link" style={{ color: record.obsoleted ? '#1890ff' : '#fa8c16' }} >删除</a>
                            </Popconfirm>
                        </Space>
                    ),
                },
            ],
            data: [], //储存axios获取到的数据
        }
    }

    //关闭新增信息对话框
    onClose = () => {
        this.setState({
            imageurl:"",
            visible: false
        });
        message.error('取消操作');
    };
  
    //显示新增信息抽屉
    showDrawer = () => {
        this.setState({
            visible: true
        });
    };
  

    //将数据显示在初始页面
    componentDidMount() {
        this.readData()
    }

    //实现读取数据——————get
    readData() {
        get('https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/lunbo_image',
            {
                "X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                'Content-Type': 'application/json'
            }
        )
            .then(res => {
                console.log(res)
                this.setState({
                    data: res.results

                })
                res.results.forEach((r, i) => {

                    r.key = i;
                });
            }).catch(error => {
                console.log(error)
            })
    }



    //新增数据——————post
    //新增、修改数据时提交失败时的提示信息
    onFinishFailed = (errorInfo) => {
        console.log(this.state)
        // console.log('Failed:', this.state.imageUrl);
        message.error("按照格式要求输入")
    };
   
    postData = () => {
        // console.log(this.state)
        const formData = new FormData();
        formData.append('file', this.state.image);
        formData.append('name', this.state.image.name);
        axios.post('https://api.leancloud.cn/1.1/files/file', formData, {
            headers: {
                " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                'Content-Type': 'image/jpeg'
            }
        }).then(response => {
            console.log(response)
            axios.post("https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/lunbo_image", {
              
               
                imageurl: response.data.url,
               
            }, {
                headers: {
                    " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                    "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                    'Content-Type': 'application/json'
                }
            }).then(res => {
                message.success('添加成功');
                // console.log('添加成功')
                this.readData()
                this.setState({
                    visible: false
                });
                this.formRef.current.resetFields() //新增成功后清空输入框中的数据，避免下次点击新增时出现上次输入的数据
            }).catch(error => {

                message.error("按照格式要求输入")
                console.log(this.state)

            });
        })


    
    }

    //上传图片
    handleChangeimage = (event) => {
        const file = event.target.files[0];
        const reader = new FileReader();

        reader.onloadend = () => {
            this.setState({
                image: file
            })


            this.setState({
                imageUrl: reader.result
            })
        };

        if (file instanceof Blob) {
            reader.readAsDataURL(file);
        }



    };
    // // 实现删除————————delete
    deleteData = (id) => {
        console.log(id)
        axios.delete(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/lunbo_image/${id}`,{
            headers: {
                " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                    "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                    'Content-Type': 'application/json'
                
            }
        }) //id前面的 / 不能省略
            .then(res => {
                message.success('删除成功');
                // console.log('删除成功')
                this.readData()
            }).catch(e => {
                message.success("删除失败了，请查看！！！")
            })
    };

   


    //实现修改数据——put或patch
   

    render() {
        let data = this.state.data;
        let columns = this.state.columns;
        let { xiangqing, imageUrl, classs, people_id, price, bcid } = this.state;
        return (
            <div className="App">
                <Button type="primary" onClick={this.showDrawer.bind(this)} >添加信息 </Button>
                
                <Divider plain>轮播图片</Divider>
                <Table columns={columns} dataSource={data} pagination={{ pageSize: 10 }} >   </Table>

                <Drawer title="添加个人信息" onClose={this.onClose} visible={this.state.visible}>
                    <Form ref={this.formRef} onFinish={this.postData} onFinishFailed={this.onFinishFailed} autoComplete="off" >
                        
                        <Form.Item
                            name="image"
                            label="图片"
                            rules={[{ required: false, message: '图片', },]}  >
                            <Input placeholder="图片" type='file' id="image"  onChange={this.handleChangeimage} title='图片' />
                            
                           <img className='pushimage' src={imageUrl}  style={{ maxWidth:'200px' }} alt="商品图片" />
                        </Form.Item>
                       

                        <Button onClick={this.onClose.bind(this)}>取消</Button>
                        <Button htmlType="submit" type="primary">完成 </Button>
                    </Form>
                </Drawer>

            </div>
        );
    }
}
export default Class;

